package com.zmn.oms.business.impl.masternotice;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.masternotice.MasterNoticeHistoryBService;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.model.entity.masternotice.MasterNoticeHistory;
import com.zmn.oms.model.entity.masternotice.MasterNoticeHistoryQuery;
import com.zmn.oms.model.entity.tipsconfig.PictureTipsConfig;
import com.zmn.oms.model.entity.tipsconfig.PictureTipsConfigQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.masternotice.MasterNoticeHistoryService;
import com.zmn.oms.services.interfaces.tipsconfig.PictureTipsConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @title: 图片历史记录实现
 * @author:Rananquan
 * @date:2022/8/3 17:03
 */
@Slf4j
@Service
public class MasterNoticeHistoryBServiceImpl implements MasterNoticeHistoryBService {

    private static final String TAG = "图片历史";

    @Resource
    private MasterNoticeHistoryService masterNoticeHistoryService;

    @Resource
    private PictureTipsConfigService pictureTipsConfigService;

    @Resource
    private RedisTemplate<String,Integer> pictureTipsConfigRestTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getNewTipSrc(OrderWork orderWork) {
        // 获取轮播图片
        List<PictureTipsConfig> pictureTipsConfigsList = this.getPictureTipsConfigsList(orderWork);
        if(CollectionUtil.isNullOrEmpty(pictureTipsConfigsList)){
            return GlobalConsts.SPLITER_EMPTY;
        }

        // 获取轮播图片历史记录
        List<MasterNoticeHistory> masterNoticeHistoryList = this.getMasterNoticeHistoryList(orderWork,pictureTipsConfigsList);

        // 记录为空直接保存
        if(CollectionUtil.isNullOrEmpty(masterNoticeHistoryList)){
            PictureTipsConfig pictureTipsConfig = pictureTipsConfigsList.get(GlobalConsts.NONE);

            saveAndRecord(orderWork,pictureTipsConfig);

            return pictureTipsConfig.getSrc();
        }

        // 获取当前轮播图片ID
        Integer configId = pictureTipsConfigRestTemplate.opsForValue().get(String.format(RedisKeyConsts.ORDER_MASTER_NOTICE_HISTORY_CURRENT,orderWork.getOrderId()));
        int size = pictureTipsConfigsList.size()-1;
        // 获取下一张图片
        int index = 0;
        for (int i = 0; i <=size; i++) {
            Integer id = pictureTipsConfigsList.get(i).getId();
            if(Objects.equals(configId,id)){
                index = i;

                break;
            }
        }

        PictureTipsConfig currentPictureTipsConfig;
        // 如果下标等于最后一个
        if(Objects.equals(index,size)){
            currentPictureTipsConfig = pictureTipsConfigsList.get(GlobalConsts.NONE);
        }else{
            // 获取下一张图片
            currentPictureTipsConfig = pictureTipsConfigsList.get(index+1);
        }


        // 判断记录是否存在
        Optional<MasterNoticeHistory> masterNoticeHistoryOptional = masterNoticeHistoryList.stream()
                .filter(masterNoticeHistory -> Objects.equals(currentPictureTipsConfig.getId(), masterNoticeHistory.getConfigId()))
                .findFirst();
        if(!masterNoticeHistoryOptional.isPresent()){
            saveAndRecord(orderWork,currentPictureTipsConfig);
        }else{
            MasterNoticeHistory masterNoticeHistory = masterNoticeHistoryOptional.get();
            masterNoticeHistory.setUpdateTime(DateUtil.getNow());

            updateAndRecord(orderWork,currentPictureTipsConfig,masterNoticeHistory);
        }

        return currentPictureTipsConfig.getSrc();
    }


    /**
     * 获取图片配置
     * @param orderWork
     * @return
     */
    private List<PictureTipsConfig> getPictureTipsConfigsList(OrderWork orderWork){
        PictureTipsConfigQuery pictureTipsConfigQuery = new PictureTipsConfigQuery();
        pictureTipsConfigQuery.setServCategId(orderWork.getServCategId());

        if(NumberUtil.isNotNullOrZero(orderWork.getShowProductId())){
            // 前台产品
            pictureTipsConfigQuery.setCategId(orderWork.getShowCategId());
        }else{
            // 后台产品
            pictureTipsConfigQuery.setCategId(orderWork.getCategId());
        }

        log.info("[{}]，根据servCategId和categId查询图片配置入参：{}",TAG,JSON.toJSONString(orderWork));

        List<PictureTipsConfig> pictureTipsConfigsList = pictureTipsConfigService.listByQuery(pictureTipsConfigQuery);
        if(CollectionUtil.isNullOrEmpty(pictureTipsConfigsList)){
            return Collections.emptyList();
        }

        // 从小到大排序
        return pictureTipsConfigsList.stream().sorted(Comparator.comparing(PictureTipsConfig::getSort)).collect(Collectors.toList());
    }


    /**
     * 查询师傅历史记录
     * @param orderWork
     * @param pictureTipsConfigsList
     * @return
     */
    private List<MasterNoticeHistory> getMasterNoticeHistoryList(OrderWork orderWork,List<PictureTipsConfig> pictureTipsConfigsList){
        MasterNoticeHistoryQuery query = new MasterNoticeHistoryQuery();
        query.setMasterId(orderWork.getMasterId());

        // 前台产品
        if(NumberUtil.isNotNullOrZero(orderWork.getShowProductId())){
            query.setCategId(orderWork.getShowCategId());
        }else{
            // 后台产品
            query.setCategId(orderWork.getCategId());
        }

        List<MasterNoticeHistory> masterNoticeHistories = masterNoticeHistoryService.listByQuery(query);
        if(CollectionUtil.isNullOrEmpty(masterNoticeHistories)){
            return Collections.emptyList();
        }

        // 删除无用的历史记录
        List<Integer> configIds = masterNoticeHistories.stream().map(MasterNoticeHistory::getConfigId).filter(configId ->
                pictureTipsConfigsList.stream()
                .noneMatch(pictureTipsConfig -> Objects.equals(pictureTipsConfig.getId(), configId))
        ).collect(Collectors.toList());
        if(CollectionUtil.isNotNullOrEmpty(configIds)){
            masterNoticeHistoryService.deleteBatch(configIds);
        }

        // 过滤掉无用的历史记录
        return masterNoticeHistories.stream().filter(masterNoticeHistory -> pictureTipsConfigsList.stream()
                .anyMatch(pictureTipsConfig -> Objects.equals(pictureTipsConfig.getId(), masterNoticeHistory.getConfigId()))
        ).collect(Collectors.toList());
    }


    private void saveNewMasterNoticeHistory(OrderWork orderWork, Integer configId){
        MasterNoticeHistory masterNoticeHistory = new MasterNoticeHistory();
        masterNoticeHistory.setMasterId(orderWork.getMasterId());
        masterNoticeHistory.setServCategId(orderWork.getServCategId());
        // 前台产品
        if(NumberUtil.isNotNullOrZero(orderWork.getShowProductId())){
            masterNoticeHistory.setCategId(orderWork.getShowCategId());
        }else{
            // 后台产品
            masterNoticeHistory.setCategId(orderWork.getCategId());
        }
        masterNoticeHistory.setConfigId(configId);
        masterNoticeHistory.setCreateTime(DateUtil.getNow());
        masterNoticeHistory.setUpdateTime(DateUtil.getNow());

        masterNoticeHistoryService.insert(masterNoticeHistory);
    }


    /**
     * 保存并且记录
     * @param orderWork
     * @param pictureTipsConfig
     */
    private void saveAndRecord(OrderWork orderWork,PictureTipsConfig pictureTipsConfig){
        log.info("[{}]，当前订单号：{}，图片配置：{}",TAG,orderWork.getOrderId(), JSON.toJSON(pictureTipsConfig));

        // 记录当前轮播的图片
        pictureTipsConfigRestTemplate.opsForValue().set(String.format(RedisKeyConsts.ORDER_MASTER_NOTICE_HISTORY_CURRENT,orderWork.getOrderId()),pictureTipsConfig.getId(),5,TimeUnit.DAYS);

        saveNewMasterNoticeHistory(orderWork,pictureTipsConfig.getId());
    }


    private void updateAndRecord(OrderWork orderWork,PictureTipsConfig pictureTipsConfig,MasterNoticeHistory masterNoticeHistory){
        log.info("[{}]，当前订单号：{}，图片配置：{}",TAG,orderWork.getOrderId(), JSON.toJSON(pictureTipsConfig));

        // 记录当前轮播的图片
        pictureTipsConfigRestTemplate.opsForValue().set(String.format(RedisKeyConsts.ORDER_MASTER_NOTICE_HISTORY_CURRENT,orderWork.getOrderId()),pictureTipsConfig.getId(),5,TimeUnit.DAYS);

        masterNoticeHistoryService.updateByKey(masterNoticeHistory);
    }
}
